<template>
  <div class="common-search-container">
    <el-config-provider :locale="elementPlusLocale">
      <el-form :inline="true" :model="searchModel" class="search-form" :label-width="labelWidth">
        <!-- 始终显示的搜索项 -->
        <template v-for="(item, index) in visibleSearchItems" :key="index">
          <!-- 输入框类型 -->
          <el-form-item v-if="item.type === 'el-input'" :label="item.label">
            <el-input 
              v-model="searchModel[item.prop]" 
              :placeholder="item.placeholder" 
              clearable 
              :style="getItemStyle(item)">
            </el-input>
          </el-form-item>
          
          <!-- 下拉框类型 -->
          <el-form-item v-else-if="item.type === 'el-select'" :label="item.label">
            <el-select 
              v-model="searchModel[item.prop]" 
              :placeholder="item.placeholder" 
              clearable 
              :style="getItemStyle(item)"
              :filterable="item.filterable !== false"
              :remote="item.remote === true"
              :remote-method="item.remote ? (query) => handleRemoteSearch(query, item) : undefined"
              :loading="item.loading || false"
              :reserve-keyword="item.reserveKeyword !== false"
              :remote-show-suffix="item.remoteShowSuffix !== false"
              :allow-create="item.allowCreate === true"
              :multiple="item.multiple === true"
              :collapse-tags="item.collapseTags === true"
              :collapse-tags-tooltip="item.collapseTagsTooltip === true"
              :max-collapse-tags="item.maxCollapseTags || 1"
            >
              <el-option 
                v-for="option in item.remote ? item.remoteOptions || item.options : item.options" 
                :key="option.value" 
                :label="option.label" 
                :value="option.value">
              </el-option>
            </el-select>
          </el-form-item>
          
          <!-- 日期类型 -->
          <el-form-item v-else-if="item.type === 'el-date-picker'" :label="item.label">
            <el-date-picker
              v-model="searchModel[item.prop]"
              :type="item.dateType || 'date'"
              :placeholder="item.placeholder"
              :style="getItemStyle(item)"
              :format="item.format || 'YYYY-MM-DD'"
              :value-format="item.valueFormat || 'YYYY-MM-DD'"
              :shortcuts="dateShortcuts"
              clearable
            />
          </el-form-item>

          <!-- 日期范围类型 -->
          <el-form-item v-else-if="item.type === 'el-date-picker-range'" :label="item.label">
            <el-date-picker
              v-model="searchModel[item.prop]"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :style="getItemStyle(item)"
              :format="item.format || 'YYYY-MM-DD'"
              :value-format="item.valueFormat || 'YYYY-MM-DD'"
              :shortcuts="dateRangeShortcuts"
              clearable
            />
          </el-form-item>
          
          <!-- 自定义插槽类型 -->
          <el-form-item v-else-if="item.type === 'slot'" :label="item.label">
            <slot :name="item.slotName" :form="searchModel"></slot>
          </el-form-item>
          
          <!-- 地区级联选择器类型 -->
          <el-form-item v-else-if="item.type === 'region-cascader'" :label="item.label">
            <region-cascader
              v-model="searchModel[item.prop]"
              :placeholder="item.placeholder"
              :level="item.level || 3"
              :separator="item.separator || '/'"
              :use-code-data="item.useCodeData || false"
              :return-code="item.returnCode || false"
              :filterable="item.filterable !== false"
              :clearable="item.clearable !== false"
              :style="getItemStyle(item)"
            />
          </el-form-item>
        </template>
        
        <!-- 展开后显示的搜索项 -->
        <template v-if="isExpanded">
          <template v-for="(item, index) in hiddenSearchItems" :key="index + visibleSearchItems.length">
            <!-- 输入框类型 -->
            <el-form-item v-if="item.type === 'el-input'" :label="item.label">
              <el-input 
                v-model="searchModel[item.prop]" 
                :placeholder="item.placeholder" 
                clearable 
                :style="getItemStyle(item)">
              </el-input>
            </el-form-item>
            
            <!-- 下拉框类型 -->
            <el-form-item v-else-if="item.type === 'el-select'" :label="item.label">
              <el-select 
                v-model="searchModel[item.prop]" 
                :placeholder="item.placeholder" 
                clearable 
                :style="getItemStyle(item)"
                :filterable="item.filterable !== false"
                :remote="item.remote === true"
                :remote-method="item.remote ? (query) => handleRemoteSearch(query, item) : undefined"
                :loading="item.loading || false"
                :reserve-keyword="item.reserveKeyword !== false"
                :remote-show-suffix="item.remoteShowSuffix !== false"
                :allow-create="item.allowCreate === true"
                :multiple="item.multiple === true"
                :collapse-tags="item.collapseTags === true"
                :collapse-tags-tooltip="item.collapseTagsTooltip === true"
                :max-collapse-tags="item.maxCollapseTags || 1"
              >
                <el-option 
                  v-for="option in item.remote ? item.remoteOptions || item.options : item.options" 
                  :key="option.value" 
                  :label="option.label" 
                  :value="option.value">
                </el-option>
              </el-select>
            </el-form-item>
            
            <!-- 日期类型 -->
            <el-form-item v-else-if="item.type === 'el-date-picker'" :label="item.label">
              <el-date-picker
                v-model="searchModel[item.prop]"
                :type="item.dateType || 'date'"
                :placeholder="item.placeholder"
                :style="getItemStyle(item)"
                :format="item.format || 'YYYY-MM-DD'"
                :value-format="item.valueFormat || 'YYYY-MM-DD'"
                :shortcuts="dateShortcuts"
                clearable
              />
            </el-form-item>

            <!-- 日期范围类型 -->
            <el-form-item v-else-if="item.type === 'el-date-picker-range'" :label="item.label">
              <el-date-picker
                v-model="searchModel[item.prop]"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :style="getItemStyle(item)"
                :format="item.format || 'YYYY-MM-DD'"
                :value-format="item.valueFormat || 'YYYY-MM-DD'"
                :shortcuts="dateRangeShortcuts"
                clearable
              />
            </el-form-item>
            
            <!-- 自定义插槽类型 -->
            <el-form-item v-else-if="item.type === 'slot'" :label="item.label">
              <slot :name="item.slotName" :form="searchModel"></slot>
            </el-form-item>
            
            <!-- 地区级联选择器类型 -->
            <el-form-item v-else-if="item.type === 'region-cascader'" :label="item.label">
              <region-cascader
                v-model="searchModel[item.prop]"
                :placeholder="item.placeholder"
                :level="item.level || 3"
                :separator="item.separator || '/'"
                :use-code-data="item.useCodeData || false"
                :return-code="item.returnCode || false"
                :filterable="item.filterable !== false"
                :clearable="item.clearable !== false"
                :style="getItemStyle(item)"
              />
            </el-form-item>
          </template>
        </template>
        
        <!-- 操作按钮区域 -->
        <el-form-item>
          <el-button type="primary" @click="handleSearch" class="search-btn">查询</el-button>
          <el-button @click="resetSearchForm" class="reset-btn">重置</el-button>
          <el-button 
            v-if="needShowExpandButton" 
            type="text" 
            @click="toggleExpand" 
            class="expand-btn"
          >
            {{ isExpanded ? '收起' : '展开' }}
            <el-icon>
              <component :is="isExpanded ? 'ArrowUp' : 'ArrowDown'" />
            </el-icon>
          </el-button>
        </el-form-item>
      </el-form>
    </el-config-provider>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, nextTick, onUnmounted } from 'vue'
import { ArrowDown, ArrowUp } from '@element-plus/icons-vue'
import { ElConfigProvider } from 'element-plus'
import { elementPlusLocale } from '@/utils/i18n-config'
import { RegionCascader } from '@/components/common'

const props = defineProps({
  // 搜索项配置
  searchItems: {
    type: Array,
    required: true,
  },
  // 搜索表单数据
  modelValue: {
    type: Object,
    required: true
  },
  // 全局搜索项宽度设置
  itemWidth: {
    type: [String, Number],
    default: '230px'
  },
  // 表单标签宽度
  labelWidth: {
    type: [String, Number],
    default: 'auto'
  }
})

const emit = defineEmits(['update:modelValue', 'search', 'reset', 'remote-search'])

// 搜索表单数据
const searchModel = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emit('update:modelValue', val)
  }
})

// 是否展开更多搜索项
const isExpanded = ref(false)

// 切换展开/收起状态
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value
}

// 默认可见的搜索项
const visibleSearchItems = computed(() => {
  return props.searchItems.filter(item => item.defaultVisible)
})

// 默认隐藏的搜索项
const hiddenSearchItems = computed(() => {
  return props.searchItems.filter(item => !item.defaultVisible)
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '今天',
    value: new Date(),
  },
  {
    text: '昨天',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24)
      return date
    },
  },
  {
    text: '一周前',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
      return date
    },
  }
]

// 日期范围快捷选项
const dateRangeShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

// 获取搜索项样式，支持全局和单项宽度设置
const getItemStyle = (item) => {
  // 如果项目有自己的宽度设置，优先使用
  if (item.width) {
    return { width: typeof item.width === 'number' ? `${item.width}px` : item.width }
  }
  // 否则使用全局宽度设置
  return { width: typeof props.itemWidth === 'number' ? `${props.itemWidth}px` : props.itemWidth }
}

// 处理搜索
const handleSearch = () => {
  // 处理多选字段的空值
  const processedData = { ...searchModel.value }
  props.searchItems.forEach(item => {
    if (item.multiple && Array.isArray(processedData[item.prop]) && processedData[item.prop].length === 0) {
      // 如果是多选且当前值为空数组，则设置为undefined
      processedData[item.prop] = undefined
    }
  })
  
  emit('search', processedData)
}

// 重置搜索表单
const resetSearchForm = () => {
  // 重置表单，多选字段需要重置为空数组
  for (const key in searchModel.value) {
    const item = props.searchItems.find(i => i.prop === key)
    if (item && item.multiple) {
      searchModel.value[key] = []
    } else {
      searchModel.value[key] = ''
    }
  }
  
  // 日期范围重置为空数组
  props.searchItems.forEach(item => {
    if (item.type === 'el-date-picker-range') {
      searchModel.value[item.prop] = []
    }
  })
  
  // 触发重置事件
  emit('reset')
}

// 搜索表单容器ref
const searchFormRef = ref(null)

// 窗口尺寸变化监听器
let resizeObserver = null

// 是否需要显示展开按钮（自适应）
const needShowExpandButton = ref(false)

// 检测是否需要显示展开按钮
const checkNeedExpand = () => {
  if (hiddenSearchItems.value.length === 0) {
    // 没有隐藏项，不需要显示展开按钮
    needShowExpandButton.value = false
    return
  }
  
  // 获取表单容器
  const formEl = document.querySelector('.search-form')
  if (!formEl) return
  
  // 获取所有表单项
  const formItems = formEl.querySelectorAll('.el-form-item')
  if (!formItems.length) return
  
  // 获取表单容器的宽度
  const formWidth = formEl.offsetWidth
  
  // 计算所有可见项(包括操作按钮)的总宽度
  let totalVisibleWidth = 0
  let rightButtonsWidth = 0
  
  // 检查每个表单项
  let visibleItemsCount = 0
  for (let i = 0; i < formItems.length; i++) {
    const item = formItems[i]
    // 检查是否是按钮操作区域
    if (item.contains(formEl.querySelector('.search-btn'))) {
      rightButtonsWidth = item.offsetWidth
      continue
    }
    
    // 如果当前不是展开状态，则只考虑默认可见项
    if (!isExpanded.value && visibleItemsCount >= visibleSearchItems.value.length) {
      continue
    }
    
    totalVisibleWidth += item.offsetWidth
    visibleItemsCount++
  }
  
  // 添加右侧按钮的宽度
  totalVisibleWidth += rightButtonsWidth
  
  // 检查是否需要换行
  // 如果可见项的总宽度超过表单容器宽度，则需要显示"展开"按钮
  needShowExpandButton.value = totalVisibleWidth > formWidth || hiddenSearchItems.value.length > 0
}

// 监听窗口大小变化
onMounted(() => {
  nextTick(() => {
    // 初始检查
    checkNeedExpand()
    
    // 设置resize观察器
    resizeObserver = new ResizeObserver(() => {
      checkNeedExpand()
    })
    
    const formEl = document.querySelector('.search-form')
    if (formEl) {
      resizeObserver.observe(formEl)
    }
  })
})

// 在组件销毁时清理观察器
onUnmounted(() => {
  if (resizeObserver) {
    resizeObserver.disconnect()
  }
})

// 监听展开状态变化
watch(isExpanded, () => {
  nextTick(() => {
    checkNeedExpand()
  })
})

// 处理远程搜索
const handleRemoteSearch = (query, item) => {
  if (!query) return;
  
  // 通过自定义事件通知父组件执行远程搜索
  emit('remote-search', {
    query,
    prop: item.prop,
    item
  });
}
</script>

<style lang="scss" scoped>
.common-search-container {
  background-color: #fff;
  margin-bottom: 15px;
  border-bottom: 1px solid #dcdfe6;
  
  .search-form {
    display: flex;
    flex-wrap: wrap;
    
    :deep(.el-form-item__label) {
      font-size: 14px;
    }
    
    .el-form-item {
      margin-bottom: 20px;
      margin-right: 15px;
    }
    
    .search-btn, .reset-btn {
      width: 80px;
      margin-left: 10px;
    }
    
    .expand-btn {
      margin-left: 10px;
      display: flex;
      align-items: center;
      
      .el-icon {
        margin-left: 5px;
      }
    }
  }
}
</style> 